import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'dart:async';  // 定时器Timer使用此库

// 消息弹框
import 'package:fluttertoast/fluttertoast.dart';

import '../../services/ScreenAdapter.dart';
import '../../config/Config.dart';
import '../../widget/MyButton.dart';
import '../../widget/MyTextField.dart';

class RegisterSecondPage extends StatefulWidget {
  final Map arguments;
  RegisterSecondPage({this.arguments});

  @override
  State<StatefulWidget> createState() => RegisterSecondState(tel: arguments['tel']);
}

class RegisterSecondState extends State<RegisterSecondPage> {
  String tel;
  String code;
  bool sendCodeBtn = false;   // 是否发送验证码
  int seconds = 10;  // 倒计时秒数
  Timer t;   // 定时器
  RegisterSecondState({this.tel=''});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('手机快速注册-第二步')),
      body: Container(
        margin: EdgeInsets.all(20),
        child: ListView(
          children: [
            // 提示
            Container(
              margin: EdgeInsets.only(bottom: 20),
              child: Text('请输入$tel收到的验证码：',style: TextStyle(fontWeight: FontWeight.w900)),
            ),

            // 请输入验证码
            Row(
              children: [
                Expanded(
                  flex: 5,
                    child: MyTextField(
                      text: '请输入验证码',
                      cb: (value){
                        this.setState(() {
                          code = value;
                        });
                      },
                    )
                ),
                Expanded(
                    flex: 4,
                    child: this.sendCodeBtn ? MyButton(
                      text: '重新发送',
                      color: Colors.black12,
                      textColor: Colors.black38,
                      height: ScreenAdapter.height(170),
                      rightMargin: 0,
                      borderRadius: 0,
                      fontSize: 14,
                      cb: _againSendCode,
                    ) : MyButton(
                      text: '(${this.seconds})秒后重新发送',
                      color: Colors.black12,
                      textColor: Colors.black38,
                      height: ScreenAdapter.height(170),
                      rightMargin: 0,
                      borderRadius: 0,
                      fontSize: 14,
                    )
                )
              ],
            ),

            SizedBox(height: 20),

            // 下一步
            MyButton(
              text: '下一步',
              color: Colors.black12,
              height: ScreenAdapter.height(180),
              textColor: Colors.black54,
              leftMargin: 0,
              rightMargin: 0,
              borderRadius: 0,
              cb: _verCode,
            ),

            SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text('遇到问题？您可以', style: TextStyle(color: Colors.black54)),
                Text('联系客服',
                    style: TextStyle(
                      color: Colors.black87,
                      fontSize: 12,
                      decoration: TextDecoration.underline,
                    ))
              ],
            ),

          ],
        ),
      ),
    );
  }

  @override
  initState(){
    super.initState();

    // 倒计时
    _showTime();

  }

  @override
  void dispose() {
    super.dispose();

    // 定时器尚未结束时，返回上一页，主动销毁定时器
    this.t.cancel();
  }

  // 倒计时，显示时间
  _showTime(){
    this.t = Timer.periodic(Duration(
        milliseconds: 1000   // 毫秒
    ),(timer){
      this.setState(() {
        this.seconds--;
        if(this.seconds == 0) {
          // 清空定时器
          this.t.cancel();
          this.sendCodeBtn = true;
        }
      });
    });
  }

  // 验证码过时，点击再次发送验证码
  _againSendCode() async {
    if(this.sendCodeBtn){
      this.setState(() {
        this.sendCodeBtn = false;
        this.seconds = 10;
        this._showTime();
      });
      var api = Config.domain + 'api/sendCode';
      var response = await Dio().post(api,data:{"tel":this.tel});
      var res = response.data;
      if(res['success']){
        print(res);
      }else {
        // 弹框提示
        Fluttertoast.showToast(
          msg: "${res['message']}",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
        );
      }

    }
  }

  // 点击下一步，验证验证码输入是否正确
  _verCode() async {
    var api = Config.domain + 'api/validateCode';
    var response = await Dio().post(api,data: {"tel": this.tel, "code":this.code});
    var res = response.data;

    if (res['success']){
      Navigator.pushNamed(context, '/registerThird',arguments: {
        "tel":this.tel,"code":this.code
      });
    } else {
      // 弹框提示
      Fluttertoast.showToast(
        msg: "${res['message']}",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
      );
    }
  }

}
